package com.xiubai.appforpda.activitys;

import android.app.Dialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.xiubai.appforpda.R;
import com.xiubai.appforpda.db.DatabaseUtils;
import com.xiubai.appforpda.entity.BaseEntity;
import com.xiubai.appforpda.entity.BaseResultEntity;
import com.xiubai.appforpda.entity.SQLDevicesReturnBean;
import com.xiubai.appforpda.entity.SQLMainPamInventBean;
import com.xiubai.appforpda.entity.SQLNCGetUseBean;
import com.xiubai.appforpda.entity.SQLOrgPersonBean;
import com.xiubai.appforpda.entity.SQLOrgStructureBean;
import com.xiubai.appforpda.entity.SQLPamAssetBean;
import com.xiubai.appforpda.entity.SQLPamInvenBean;
import com.xiubai.appforpda.entity.SQLPamLocationBean;
import com.xiubai.appforpda.entity.SQLPamReturnStatusBean;
import com.xiubai.appforpda.entity.SQLPamStatusBean;
import com.xiubai.appforpda.entity.WebAssetEntity;
import com.xiubai.appforpda.entity.WebLocationEntity;
import com.xiubai.appforpda.entity.WebMainPamInventEntity;
import com.xiubai.appforpda.entity.WebNCGetUseEntity;
import com.xiubai.appforpda.entity.WebOrgStructureEntity;
import com.xiubai.appforpda.entity.WebPamInventEntity;
import com.xiubai.appforpda.entity.WebPamReturnStatusEntity;
import com.xiubai.appforpda.entity.WebPamStatusEntity;
import com.xiubai.appforpda.entity.WebPersonEntity;
import com.xiubai.appforpda.entity.WebSyncResultEntity;
import com.xiubai.appforpda.jack.utils.AppConstants;
import com.xiubai.appforpda.jack.utils.JsonParser;
import com.xiubai.appforpda.jack.utils.Trace;
import com.xiubai.appforpda.jack.utils.Utils;
import com.xiubai.appforpda.jack.utils.WebServiceDataUtils;
import com.xiubai.appforpda.utils.ClickUtil;
import com.xiubai.appforpda.utils.DisplayUtil;
import com.xiubai.appforpda.utils.ErrorMsgException;
import com.xiubai.appforpda.webutils.WebServiceHelper;
import com.xiubai.appforpda.widget.CustomDialog;
import com.xiubai.appforpda.widget.CustomDialogListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.serialization.SoapObject;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

public class SyncActivity extends BaseActivity implements View.OnClickListener {

    private View tv_data_callback;
    private View tv_data_fetch;
    private View tv_data_back;
    private TextView tv_name;
    private CustomDialog progressDialog;
    private CustomDialog successDialog;
    private int return_count = 0;  //
    private int current = 0; // 盘点
    private int getuse_count = 0;//领用

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sync);
        initView();
    }

    private void initView() {
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_name.setText("经办人: " + AppConstants.USER_NAME);
        tv_data_callback = findViewById(R.id.tv_data_callback);
        tv_data_fetch = findViewById(R.id.tv_data_fetch);
        tv_data_back = findViewById(R.id.tv_data_back);

        tv_data_callback.setOnClickListener(this);
        tv_data_fetch.setOnClickListener(this);
        tv_data_back.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        if (ClickUtil.isFastDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.tv_data_fetch:
                fetchData();
                break;
            case R.id.tv_data_callback:
                callbackData();
                break;
            case R.id.tv_data_back:
                finish();
                break;
            case R.id.btn_data_confirm:
                dialogDismiss(successDialog);
                break;
        }
    }

    private void dialogDismiss(Dialog dialog) {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    /**
     * 回传数据
     */
    private void callbackData() {
//        showProgressDialog("回传NC数据中...");
        returnDevices();

    }

    private void returnDevices() {
        AsyncTask<Integer,Integer,Integer> asyncTask = new AsyncTask<Integer, Integer, Integer>() {
            String msg = "";
            String status = "";

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                showProgressDialog("回传NC数据中...");
            }

            @Override
            protected Integer doInBackground(Integer... integers) {

                try {
                    List<SQLDevicesReturnBean> sqlDevicesReturnBeans = DatabaseUtils.getHelper().queryAll(SQLDevicesReturnBean.class);
                    List<SQLNCGetUseBean> sqlncGetUseBeans = DatabaseUtils.getHelper().queryAll(SQLNCGetUseBean.class);
                    List<SQLMainPamInventBean> sqlMainPamInventBeans = DatabaseUtils.getHelper().queryAll(SQLMainPamInventBean.class);
                    if (sqlDevicesReturnBeans == null && sqlMainPamInventBeans == null && sqlncGetUseBeans == null) {
                        return 1;
                    }
                    int count = 0;
                    if (sqlDevicesReturnBeans != null) {
                        return_count = sqlDevicesReturnBeans.size();
                        for (SQLDevicesReturnBean bean : sqlDevicesReturnBeans) {
                            // 没有标记为归还成功的才需要回传
                            if (!"Y".equals(bean.my_status)) {
                                count++;
                                callReturnWs(bean);
                                System.out.println("SyncTask归还:" + bean.toString());
                            }
                        }
                    }

                    if (sqlncGetUseBeans != null) {
                        for (SQLNCGetUseBean bean : sqlncGetUseBeans) {
                            if ("Y".equals(bean.my_status) && !"Y".equals(bean.return_status)) {
                                count++;
                                callGetUseWs(bean);
                                System.out.println("SyncTask领用:" + bean.toString());
                            }
                        }
                    }

                    if (sqlMainPamInventBeans != null) {

                        List<SQLMainPamInventBean> needSync = new ArrayList<>();
                        for (SQLMainPamInventBean bean : sqlMainPamInventBeans) {
                            // 增加 未盘点到的数据不回传 状态判断
                            if ("Y".equals(bean.my_status) && "Y".equals(bean.bill_status)) {
                                needSync.add(bean);
                            }
                        }
                        count = count + needSync.size();
                        if (needSync.size()> 0) {
                            callCheckWs(needSync);
                        }
                    }
                    if (count == 0) {
                        return 0;
                    }else{
                        return -1;// ok
                    }
                } catch (ErrorMsgException e) {
                    this.msg = e.msg;
                    this.status = e.status;
                    return 2;
                } catch (Exception e){
                    e.printStackTrace();
                    return 3;
                }

            }

            @Override
            protected void onPostExecute(Integer integer) {
                super.onPostExecute(integer);
                dialogDismiss(progressDialog);

                if(integer == 1){
                    Toast.makeText(SyncActivity.this, "尚未存在需要回传的数据", Toast.LENGTH_SHORT).show();
                }else if(integer == 0){
                    Toast.makeText(SyncActivity.this, "没有数据需要回传", Toast.LENGTH_SHORT).show();
                }else if(integer == 2){
                    Toast.makeText(SyncActivity.this, "失败" + status + "原因" + msg, Toast.LENGTH_SHORT).show();
                }else if(integer == 3){
                    Toast.makeText(SyncActivity.this, "数据异常", Toast.LENGTH_SHORT).show();
                }else if(integer == -1){
                    showSuccessDialog("回传完成!");
                }
            }
        }.execute();

        /*try {
            List<SQLDevicesReturnBean> sqlDevicesReturnBeans = DatabaseUtils.getHelper().queryAll(SQLDevicesReturnBean.class);
            List<SQLNCGetUseBean> sqlncGetUseBeans = DatabaseUtils.getHelper().queryAll(SQLNCGetUseBean.class);
            List<SQLMainPamInventBean> sqlMainPamInventBeans = DatabaseUtils.getHelper().queryAll(SQLMainPamInventBean.class);
            return_count = current = getuse_count = 0;
            if (sqlDevicesReturnBeans == null && sqlMainPamInventBeans == null && sqlncGetUseBeans == null) {
                Toast.makeText(this, "尚未存在需要回传的数据", Toast.LENGTH_SHORT).show();
                dialogDismiss(progressDialog);
                return;
            }
            int count = 0;
            if (sqlDevicesReturnBeans != null) {
                return_count = sqlDevicesReturnBeans.size();
                for (SQLDevicesReturnBean bean : sqlDevicesReturnBeans) {
                    // 没有标记为归还成功的才需要回传
                    if (!"Y".equals(bean.my_status)) {
                        callReturnWs(bean);
                        count++;
                        System.out.println("SyncTask归还:"+bean.toString());
                    }
                }
            }

            if (sqlncGetUseBeans != null) {
                for (SQLNCGetUseBean bean : sqlncGetUseBeans) {
                    if ("Y".equals(bean.my_status) && !"Y".equals(bean.return_status)) {
                        getuse_count++;
                        count++;
                        callGetUseWs(bean);
                        System.out.println("SyncTask领用:"+bean.toString());
                    }
                }
            }

            if (sqlMainPamInventBeans != null) {

                 List<SQLMainPamInventBean> needSync=new ArrayList<>();
                for (SQLMainPamInventBean bean : sqlMainPamInventBeans) {
                    // 增加 未盘点到的数据不回传 状态判断
                    if ("Y".equals(bean.my_status) &&
                            "Y".equals(bean.bill_status)) {
                        current++;
    //                    callCheckWs(bean);
                        needSync.add(bean);
                    }
                }
                count = count+needSync.size();
                callCheckWs(needSync);
            }
            if(count==0){
                dialogDismiss(progressDialog);
                Toast.makeText(SyncActivity.this, "没有数据需要回传", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            dialogDismiss(progressDialog);
        }*/
    }

    /**
     * 回传领用数据
     * @param mysqlncReturnBean
     */
    private void callGetUseWs(final SQLNCGetUseBean mysqlncReturnBean) {
        //通过工具类调用WebService接口
        String type = mysqlncReturnBean.billcode.substring(0, 4);
        Trace.d("type====" + type);
        LinkedHashMap<String, String> value = WebServiceDataUtils.postParameterData(type, mysqlncReturnBean.billcode, mysqlncReturnBean.pamcode, mysqlncReturnBean.usercode, mysqlncReturnBean.audtcode, mysqlncReturnBean.billdate);
        WebServiceHelper.callWebServiceSynchronized(WebServiceHelper.WEB_URL, AppConstants.METHOD_NAME, value, new WebServiceHelper.WebServiceCallBack() {
            @Override
            public void callBack(SoapObject result) {
                Trace.d("result==" + result);
                String status= "";
                String msg= "";
                if (result != null) {
                    String json = result.getProperty(0).toString();

                    try {
                        JSONObject jsonObject = new JSONObject(json);
                        System.out.println("SyncTask领用result:" + jsonObject.toString());
//                        jsonObject.remove("data");
                        if(jsonObject.has("data")){
                            JSONArray jsonArray = jsonObject.getJSONArray("data");
                            JSONObject entity = jsonArray.getJSONObject(0);

                            String billcode= "";
                            String equipcode= "";
                            if(entity.has("status")){
                                status = entity.getString("status");
                            }
                            if(entity.has("msg")){
                                msg = entity.getString("msg");
                            }
                            if(entity.has("billcode")){
                                billcode = entity.getString("billcode");
                            }
                            if(entity.has("equipcode")){
                                equipcode = entity.getString("equipcode");
                            }
                            if(status.equals("1")){
                                mysqlncReturnBean.return_status = "Y";
                                // 打开
                                DatabaseUtils.getHelper().update(SQLNCGetUseBean.class, "return_status", "Y", "pamcode=? and billcode=?", new String[]{equipcode, billcode});
                                getuse_count--;
                            }else{
                                throw  new ErrorMsgException("",msg,status);
                            }
                        }else{
                            throw new ErrorMsgException("","返回JSON格式错误,没有data",status);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        throw  new ErrorMsgException(e.getMessage(),"返回JSON格式错误",status);
                    }
                } else {
                    throw  new ErrorMsgException("","网络超时,请检查网络",status);
                }

                /*Trace.d("json====" + json);
                    BaseEntity assetBean = JsonParser.deserializeByJson(json, BaseEntity.class);
                    if (assetBean != null) {
                        if (assetBean.isSuccess()) {
                            mysqlncReturnBean.return_status = "Y";
                            // 打开
                            DatabaseUtils.getHelper().update(SQLNCGetUseBean.class, "pamcode", mysqlncReturnBean.pamcode, "return_status", "Y");
                            DatabaseUtils.getHelper().update(SQLNCGetUseBean.class,"pamcode=? and billcode=?", new String[]{bean.assetcode,bean.billcode});
                            getuse_count--;
                        } else {
                            Toast.makeText(SyncActivity.this, "失败" + assetBean.status + "原因" + assetBean.msg, Toast.LENGTH_SHORT).show();
                        }
                    }*/
            }
        });
    }

    /**
     * 设备归还
     *
     * @param bean
     */
    private void callReturnWs(final SQLDevicesReturnBean bean) {
        //通过工具类调用WebService接口
        LinkedHashMap<String, String> value = WebServiceDataUtils.postReturnParameterData(WebServiceDataUtils.POST_JYGH_TYPE, bean.assetcode, bean.audtcode, bean.audtcode, bean.billdate);
        WebServiceHelper.callWebServiceSynchronized(WebServiceHelper.WEB_URL, AppConstants.METHOD_NAME, value, new WebServiceHelper.WebServiceCallBack() {
            @Override
            public void callBack(SoapObject result) {
                Trace.d("result==" + result);
                String status= "";
                String msg= "";
                if (result != null) {
                    String json = result.getProperty(0).toString();
                    try {
                        JSONObject jsonObject = new JSONObject(json);
                        System.out.println("SyncTask领用result:" + jsonObject.toString());
                        if(jsonObject.has("data")){
                            JSONArray jsonArray = jsonObject.getJSONArray("data");
                            JSONObject entity = jsonArray.getJSONObject(0);

                            String billcode= "";
                            String equipcode= "";
                            if(entity.has("status")){
                                status = entity.getString("status");
                            }
                            if(entity.has("msg")){
                                msg = entity.getString("msg");
                            }
                            if(entity.has("billcode")){
                                billcode = entity.getString("billcode");
                            }
                            if(entity.has("equipcode")){
                                equipcode = entity.getString("equipcode");
                            }
                            if(status.equals("1")){
                                // 打开
                                bean.my_status = "Y";
                                DatabaseUtils.getHelper().update(SQLDevicesReturnBean.class,"my_status", bean.my_status,"assetcode=?", new String[]{equipcode});
                            }else{
                                throw  new ErrorMsgException("",msg,status);
                            }
                        }else{
                            throw new ErrorMsgException("","返回JSON格式错误,没有data",status);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        throw  new ErrorMsgException(e.getMessage(),"返回JSON格式错误",status);
                    }
                } else {
                    throw  new ErrorMsgException("","网络超时,请检查网络",status);
                }
/*Trace.d("json====" + json);
                    BaseEntity assetBean = JsonParser.deserializeByJson(json, BaseEntity.class);
                    if (assetBean != null) {
                        if (assetBean.isSuccess()) {
                            bean.my_status = "Y";
//                            if (DatabaseUtils.getHelper().queryByArgs(MYSQLNCReturnBean.class, "pamcode", mysqlncReturnBean.pamcode) == null) {
                            DatabaseUtils.getHelper().update(SQLDevicesReturnBean.class, "assetcode", bean.assetcode, "my_status", bean.my_status);
                            return_count--;
//                            }
                        } else {
                            dialogDismiss(progressDialog);
                            Toast.makeText(SyncActivity.this, "失败" + assetBean.status + "原因" + assetBean.msg, Toast.LENGTH_SHORT).show();
                        }
                    }*/
            }
        });

    }


    /**
     * 回传盘点数据
     * @param beans
     */
    private void callCheckWs(List<SQLMainPamInventBean> beans) {
        //通过工具类调用WebService接口
        final LinkedHashMap<String, String> value = WebServiceDataUtils.postCheckParameterData(beans);
        WebServiceHelper.callWebServiceSynchronized(WebServiceHelper.WEB_URL, AppConstants.METHOD_NAME, value, new WebServiceHelper.WebServiceCallBack() {
            @Override
            public void callBack(SoapObject result) {
                Trace.d("result==" + result);
                String status= "";
                if (result != null) {
                    String json = result.getProperty(0).toString();
                    Trace.d("json====" + json);
                    BaseEntity assetBean = JsonParser.deserializeByJson(json, BaseEntity.class);
                    if (assetBean != null) {
                        if (assetBean.isSuccess()) {
                            WebPamReturnStatusEntity webAssetEntity = JsonParser.deserializeByJson(json, WebPamReturnStatusEntity.class);
                            if (webAssetEntity != null && webAssetEntity.getData()!= null&&webAssetEntity.getData().size()>0) {
                                for(SQLPamReturnStatusBean bean: webAssetEntity.getData()){
                                    if (bean.status.equals("1")) {
                                        DatabaseUtils.getHelper().delete(SQLMainPamInventBean.class," billcode=? and (assetcode=? or assetname = ?) ", new String[]{bean.billcode,bean.assetcode,bean.assetcode});
                                    }
                                }
                            }else{
                                throw  new ErrorMsgException("","返回data没有数据",assetBean.status);
                            }
                        } else {
                            throw  new ErrorMsgException("",assetBean.msg,assetBean.status);
                        }
                    } else {
                        throw  new ErrorMsgException("","返回JSON格式错误",status);
                    }
                } else {
                    throw  new ErrorMsgException("","网络超时,请检查网络",status);
                }

            }
        });

    }


    /**
     * 抓取数据
     */
    private void fetchData() {
        AsyncTask<Integer,Integer,Integer> asyncTask = new AsyncTask<Integer, Integer, Integer>() {
            String msg = "";
            String status = "";
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                showProgressDialog("抓取NC数据中...");
            }

            @Override
            protected Integer doInBackground(Integer... integers) {

                try{

                    // 基础数据
                    callWS(AppConstants.GET_PERSON);
                    callWS(AppConstants.GET_ORG_DEPT);
                    callWS(AppConstants.GET_PAM_LOCATION);
                    callWS(AppConstants.GET_PAM_STATUS);

                    // 用户数据
                    callWS(AppConstants.GET_ASSET_DATA);
                    callWS(AppConstants.GET_USE_APPLY);
                    callWS(AppConstants.PAM_INVEN);
                    callWS(AppConstants.PAM_INVEN_B);

                }catch (ErrorMsgException e){
                    msg = e.msg;
                    status = e.status;
                    return 1;
                }catch (Exception e){
                    return 2;
                }

                return 0;
            }

            @Override
            protected void onPostExecute(Integer integer) {
                super.onPostExecute(integer);
                dialogDismiss(progressDialog);
                if(integer == 0){
                    showSuccessDialog("抓取成功!");
                }else if(integer == 1){
                    Toast.makeText(SyncActivity.this, "失败" + status + "原因" + msg, Toast.LENGTH_SHORT).show();
                }else if(integer == 2){
                    Toast.makeText(SyncActivity.this, "没有返回", Toast.LENGTH_SHORT).show();
                }
            }
        }.execute();

    }

    private void callWS(final String url) {
        Trace.d("url====" + url);
        //通过工具类调用WebService接口
        LinkedHashMap<String, String> value = WebServiceDataUtils.getParameterData(url, "1=1");
        WebServiceHelper.callWebServiceSynchronized(WebServiceHelper.WEB_URL, AppConstants.METHOD_NAME, value, new WebServiceHelper.WebServiceCallBack() {
            @Override
            public void callBack(SoapObject result) {
                Trace.d("result==" + result);
                if (result != null) {
                    String json = result.getProperty(0).toString();
                    BaseEntity assetBean = JsonParser.deserializeByJson(json, BaseEntity.class);
                    if (assetBean != null) {
                        if (assetBean.isSuccess()) {
                            // do something
                            Trace.d("成功!");
                            switch (url) {
                                case AppConstants.GET_PERSON:
                                    WebPersonEntity webPersonEntity = JsonParser.deserializeByJson(json, WebPersonEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLOrgPersonBean.class);
                                    DatabaseUtils.getHelper().saveAll(webPersonEntity.getOrg_psn());  //组织人员
                                    break;
                                case AppConstants.GET_ORG_DEPT:
                                    WebOrgStructureEntity webOrgStructureEntity = JsonParser.deserializeByJson(json, WebOrgStructureEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLOrgStructureBean.class);
                                    DatabaseUtils.getHelper().saveAll(webOrgStructureEntity.getV_org_dept()); //部门
                                    break;
                                case AppConstants.GET_PAM_LOCATION:
                                    WebLocationEntity webLocationEntity = JsonParser.deserializeByJson(json, WebLocationEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLPamLocationBean.class);
                                    DatabaseUtils.getHelper().saveAll(webLocationEntity.getPam_loc()); //位置
                                    break;
                                case AppConstants.GET_PAM_STATUS:
                                    WebPamStatusEntity pamStatusBean = JsonParser.deserializeByJson(json, WebPamStatusEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLPamStatusBean.class);
                                    DatabaseUtils.getHelper().saveAll(pamStatusBean.getPam_sta()); //状态
                                    break;
                                case AppConstants.GET_ASSET_DATA:
                                    WebAssetEntity webAssetEntity = JsonParser.deserializeByJson(json, WebAssetEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLPamAssetBean.class);
                                    DatabaseUtils.getHelper().saveAll(webAssetEntity.getPam_asset()); // 设备
                                    break;
                                case AppConstants.PAM_INVEN:
                                    WebPamInventEntity webPamInventEntity = JsonParser.deserializeByJson(json, WebPamInventEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLPamInvenBean.class);
                                    DatabaseUtils.getHelper().saveAll(webPamInventEntity.getPam_inven());//盘点单表
                                    break;
                                case AppConstants.PAM_INVEN_B:// 盘点数据表
                                    WebMainPamInventEntity webMainPamInventEntity = JsonParser.deserializeByJson(json, WebMainPamInventEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLMainPamInventBean.class);

                                    // todo 增加逻辑,如果获取到的盘点后人员为空,则将盘点前人员信息复制给盘点后人员
                                    if (webMainPamInventEntity!= null) {
                                        List<SQLMainPamInventBean> pam_inven_b = webMainPamInventEntity.getPam_inven_b();
                                        if(pam_inven_b!=null){
                                            for(SQLMainPamInventBean entity : pam_inven_b){
                                                if(entity == null || "".equals(entity.usercodeh)){
                                                    entity.usercodeh = entity.usercodeq;
                                                }
                                            }
                                        }

                                    }

                                    DatabaseUtils.getHelper().saveAll(webMainPamInventEntity.getPam_inven_b());
                                    break;
                                case AppConstants.GET_USE_APPLY: // 领用数据
                                    WebNCGetUseEntity webNCGetUseEntity = JsonParser.deserializeByJson(json, WebNCGetUseEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLNCGetUseBean.class);
                                    DatabaseUtils.getHelper().saveAll(webNCGetUseEntity.getV_pam_assign());
                                    break;
                            }
                        } else {
                            throw new ErrorMsgException("",assetBean.msg,assetBean.status);
                        }
                    } else {
                        throw new ErrorMsgException("","返回JSON数据格式异常","");
                    }
                }else {
                    if (!Utils.checkNetworkIsAvailable()) {
                        throw new ErrorMsgException("","请检查网络连接情况","");
                    }
                    throw new ErrorMsgException("","IP设置或PORT设置有误,请检查","");
                }
            }
        });
    }


    /*private static final int GET_ORG = 0;
    private static final int SUCCESS = 1;
    private static final int DELAY = 2;
    private int fetch_count;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_ORG:
                    String url = (String) msg.obj;
                    callWS(url);
                    break;
                case SUCCESS:
                    int sum = current + return_count + getuse_count;
                    if (sum > 0) {
                        showSuccessDialog("回传完成!"*//* + sum + "条数据回传失败!"*//*);
                    } else {
                        showSuccessDialog("回传完成!");
                    }
                    break;
                case DELAY:
                    Message message = Message.obtain();
                    message.what = SUCCESS;
                    handler.sendMessageDelayed(message, 2000);
                    break;
            }
        }
    };

    private void callWS(String url) {
        Trace.d("url====" + url);
        //通过工具类调用WebService接口
        LinkedHashMap<String, String> value = WebServiceDataUtils.getParameterData(url, "1=1");
        WebServiceHelper.callWebService(WebServiceHelper.WEB_URL, AppConstants.METHOD_NAME, value, new WebServiceHelper.WebServiceCallBack() {
            @Override
            public void callBack(SoapObject result) {
                Trace.d("result==" + result);
                if (result != null) {
                    String json = result.getProperty(0).toString();
                    Trace.d("json====" + json);
                    BaseEntity assetBean = JsonParser.deserializeByJson(json, BaseEntity.class);
                    if (assetBean != null) {
                        if (assetBean.isSuccess()) {
                            // do something
                            Trace.d("成功!");
                            fetch_count++;
                            Message message = Message.obtain();
                            message.what = 0;
                            switch (fetch_count) {
                                case 1:
                                    WebAssetEntity webAssetEntity = JsonParser.deserializeByJson(json, WebAssetEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLPamAssetBean.class);
                                    DatabaseUtils.getHelper().saveAll(webAssetEntity.getPam_asset());
                                    message.obj = AppConstants.PAM_INVEN;
                                    break;

                                case 2:
                                    WebPamInventEntity webPamInventEntity = JsonParser.deserializeByJson(json, WebPamInventEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLPamInvenBean.class);
                                    DatabaseUtils.getHelper().saveAll(webPamInventEntity.getPam_inven());
                                    message.obj = AppConstants.PAM_INVEN_B;
                                    break;
                                case 3:
                                    WebMainPamInventEntity webMainPamInventEntity = JsonParser.deserializeByJson(json, WebMainPamInventEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLMainPamInventBean.class);

                                    // todo 增加逻辑,如果获取到的盘点后人员为空,则将盘点前人员信息复制给盘点后人员
                                    if (webMainPamInventEntity!= null) {
                                        List<SQLMainPamInventBean> pam_inven_b = webMainPamInventEntity.getPam_inven_b();
                                        if(pam_inven_b!=null){
                                            for(SQLMainPamInventBean entity : pam_inven_b){
                                                if(entity == null || "".equals(entity.usercodeh)){
                                                    entity.usercodeh = entity.usercodeq;
                                                }
                                            }
                                        }

                                    }

                                    DatabaseUtils.getHelper().saveAll(webMainPamInventEntity.getPam_inven_b());
                                    message.obj = AppConstants.GET_USE_APPLY;
                                    break;
                                case 4:
                                    WebNCGetUseEntity webNCGetUseEntity = JsonParser.deserializeByJson(json, WebNCGetUseEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLNCGetUseBean.class);
                                    DatabaseUtils.getHelper().saveAll(webNCGetUseEntity.getV_pam_assign());
                                    showSuccessDialog("抓取成功!");
                                    break;
                            }
                            if (fetch_count >= 4) {
                                return;
                            }
                            handler.sendMessage(message);
                        } else {
                            dialogDismiss(progressDialog);
                            Toast.makeText(SyncActivity.this, "失败" + assetBean.status + "原因" + assetBean.msg, Toast.LENGTH_SHORT).show();
                        }
                    }
                } else {
                    dialogDismiss(progressDialog);
                    Toast.makeText(SyncActivity.this, "没有返回", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }*/

    /**
     * 显示抓取成功
     */
    private void showSuccessDialog(String message) {
        dialogDismiss(progressDialog);
        successDialog = new CustomDialog(this, new CustomDialogListener() {
            @Override
            public void onDialogClosed(int closeType) {

            }
        });
        successDialog.setView(LayoutInflater.from(this).inflate(R.layout.single_button_layout, null));
        TextView tv_input = (TextView) successDialog.findId(R.id.tv_single_message);
        View btn_data_confirm = successDialog.findId(R.id.btn_data_confirm);
        if (btn_data_confirm != null) {
            btn_data_confirm.setOnClickListener(this);
        }
        if (tv_input != null) {
            tv_input.setText(message);
        }
        successDialog.setCanceledOutside(false);
        successDialog.setCancelable(false);
        successDialog.show();

        dialogMatchWindow(successDialog);
    }


    /**
     * 显示抓取提示
     */
    private void showProgressDialog(String message) {
        progressDialog = new CustomDialog(this, new CustomDialogListener() {
            @Override
            public void onDialogClosed(int closeType) {

            }
        });
        progressDialog.setView(LayoutInflater.from(this).inflate(R.layout.promt_data_input_layout, null));
        TextView tv_input = (TextView) progressDialog.findId(R.id.tv_input_promt);
        if (tv_input != null) {
            tv_input.setText(message);
        }
        progressDialog.setCanceledOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.show();

        dialogMatchWindow(progressDialog);
    }

    private void dialogMatchWindow(Dialog dialog) {
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);
        window.getDecorView().setPadding(0, 0, 0, 0);

        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = DisplayUtil.dip2px(300, this.getResources().getDisplayMetrics().density);
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);

    }

}
